package com.dp.mallchat.common.chat.service.strategy;

import com.dp.mallchat.common.chat.dao.MessageDao;
import com.dp.mallchat.common.chat.domain.entity.Message;
import com.dp.mallchat.common.chat.domain.enums.MessageTypeEnum;
import com.dp.mallchat.common.chat.domain.vo.req.ReCallReq;
import com.dp.mallchat.common.chat.domain.vo.req.msg.MsgRecall;
import com.dp.mallchat.common.chat.domain.vo.resp.ReCallResp;
import com.dp.mallchat.common.chat.service.adapter.MessageAdapter;
import com.dp.mallchat.common.common.event.ReCallMsgEvent;
import com.dp.mallchat.common.user.domain.user.entity.User;
import com.dp.mallchat.common.user.service.cache.UserInfoCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author: dupeng
 * @CreateTime: 2024-07-08  19:59
 * @Description: 撤回消息
 */
@Service
@Slf4j
public class ReCallMsgHandler extends AbstractMsgHandler<ReCallReq>{

    @Autowired
    private MessageDao messageDao;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private UserInfoCache userInfoCache;


    @Override
    MessageTypeEnum getMsgType() {
        return MessageTypeEnum.RECALL;
    }

    @Override
    protected void saveMsg(Message message, ReCallReq body) {

    }

    @Override
    public Object showMsg(Message msg) {
        MsgRecall recall = msg.getExtra().getRecall();
        User userInfo = userInfoCache.get(recall.getRecallUid());
        if (!Objects.equals(recall.getRecallUid(), msg.getFromUid())) {
            return "管理员\"" + userInfo.getName() + "\"撤回了一条成员消息";
        }
        return "\"" + userInfo.getName() + "\"撤回了一条消息";
    }

    @Override
    public Object showReplyMsg(Message msg) {
        return "原消息已撤回";
    }

    @Override
    public String showContactMsg(Message msg) {
        return "撤回了一条消息";
    }

    public void recallMsg(Message message, Long uid) {
        messageDao.updateById(MessageAdapter.buildRecallMsg(message, uid));
        applicationEventPublisher.publishEvent(new ReCallMsgEvent(this, new ReCallResp(message.getId(),message.getRoomId(),uid)));
    }
}
